const gulp = require("gulp");
const XLSX = require("xlsx");
const path = require("path");
const fs = require("fs");
// const download = require("gulp-download");
const download = require("gulp-download2");
const rename = require("gulp-rename");
const url = require("url");

let errStr = "";
let sqlStr = "";

function findXlsx() {
  try {
    const xlsxDir = "./xlsx"; // xlsx文件所在目录
    const files = fs.readdirSync(xlsxDir).filter((file) => file.endsWith(".xlsx")); // 获取所有xlsx文件列表
    if (files.length > 0) {
      const fileName = files[0];
      const filePath = path.join(xlsxDir, fileName);
      console.log("\x1b[32m[成功]\x1b[0m " + `读取文件：${filePath}`);
      return filePath;
    } else {
      console.log("\x1b[31m[失败]\x1b[0m 未找到xlsx文件");
      return false;
    }
  } catch (error) {
    console.log("\x1b[31m[失败]\x1b[0m ", error);
  }
}

function saveDataToJson(data) {
  // 创建 json 目录（如果不存在）
  const dir = "./json";
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }

  const timestamp = Date.now();
  const fileName = `outfile-${timestamp}.json`;
  const filePath = `./json/${fileName}`;
  const jsonData = JSON.stringify(data, null, 2);

  fs.writeFileSync(filePath, jsonData);
  console.log(`数据保存到： ${filePath}`);
}
function saveLog(data) {
  // 创建 json 目录（如果不存在）
  const dir = "./log";
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }
  const timestamp = Date.now();
  const fileName = `log-${timestamp}.txt`;
  const filePath = `./log/${fileName}`;
  const jsonData = JSON.stringify(data, null, 2);

  fs.writeFileSync(filePath, jsonData);
  console.log(`日志保存到： ${filePath}`);
}

function saveSql(data) {
  // 创建 sql 目录（如果不存在）
  const dir = "./sql";
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }
  const timestamp = Date.now();
  const fileName = `sql-${timestamp}.txt`;
  const filePath = `./sql/${fileName}`;
  const jsonData = data;

  fs.writeFileSync(filePath, jsonData);
  console.log(`sql保存到： ${filePath}`);
}

// 定义默认任务
async function defaultTask(cb) {
  const xlsxFile = findXlsx();
  if (!xlsxFile) return cb();
  const workbook = XLSX.readFile(xlsxFile);
  const sheet_name_list = workbook.SheetNames;
  const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
  console.log("\x1b[32m[成功]\x1b[0m " + `成功生成JSON数据`);
  saveDataToJson(data); // 暂存数据用于查证

  // 创建data目录（如果不存在）
  if (!fs.existsSync("data")) {
    fs.mkdirSync("data");
  }

  console.log(data.length);
  for (let i = 0; i < data.length; i++) {
    // const downloadUrl = data[i]["公司logo"].replace(/\n/g, "");
    const downloadUrl = data[i]["url"].replace(/\\\n/g, "");
    const parsedUrl = url.parse(downloadUrl); // 解析URL
    const fileName = path.basename(parsedUrl.pathname); // 提取文件名
    const fileExtension = path.extname(fileName); // 获取文件扩展名
    const saveFileDir = "data/";
    // const saveFilePath = `${data[i]["公司简称拼音没有空格"] || "_err_" + data[i]["公司名称"]}${fileExtension}`; // 存放路径
    const saveFilePath = `${data[i]["route"] + data[i]["id"]}${fileExtension}`; // 存放路径
    sqlStr += `UPDATE c_corpinfo SET logo="${"/baseUrl/" + saveFilePath}" WHERE corpid = ${data[i]["id"]} ; \n`;
    if (fs.existsSync(saveFileDir + saveFilePath)) {
      console.log("文件已经存在，跳过");
    } else {
      console.log("开始下载", downloadUrl);
      await download(downloadUrl, {
        errorCallback: function (code) {
          console.log("\x1b[31m[下载失败]\x1b[0m ", downloadUrl);
          errStr += `[下载失败] ${downloadUrl} ${saveFilePath}`;
          if (code === 404) {
            console.error("Un oh, something bad happened!");
          } else if (code === 500) {
            console.error("Fatal exception :(");
            process.exit(1);
          } else {
            console.error(code);
          }
        },
      })
        .pipe(rename(saveFilePath))
        .pipe(gulp.dest("data/"))
        .on("end", () => {
          console.log(`Downloaded ${saveFilePath}`);
        });
      await new Promise((resolve) => setTimeout(resolve, 500)); // 等待
    }
  }

  saveLog(errStr);
  saveSql(sqlStr);
}

// 导出默认任务
exports.default = defaultTask;
